package bb.lanxing.mvp.presetner;

import android.graphics.Bitmap;
import android.text.TextUtils;
import bb.lanxing.App;
import bb.lanxing.model.database.PoiImage;
import bb.lanxing.util.Enums;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

public class PoiImagePresenter {
    public void uploadImage(long j) {
        PoiImage poiImage = (PoiImage) PoiImage.findById(PoiImage.class, Long.valueOf(j));
        if (poiImage == null) {
            return;
        }
        ArrayList arrayList = new ArrayList();
        arrayList.add(poiImage);
        sync(arrayList);
    }

    public void syncWithServer() {
        String userId = String.valueOf(App.getContext().getUserId());

        List<PoiImage> l = LitePal.where("userId = ? and isUploaded = 0", userId).find(PoiImage.class);

        sync(l);
    }

    private void sync(List<PoiImage> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        for (PoiImage poiImage : list) {
            Enums.NetworkState valueOf = TextUtils.isEmpty(poiImage.getNetType()) ? null : Enums.NetworkState.valueOf(poiImage.getNetType());
            if (precheck(poiImage) && App.networkState != Enums.NetworkState.disable && (valueOf == null || valueOf == App.networkState)) {
                if (!TextUtils.isEmpty(uploadToUpyun(poiImage))) {
                    uploadToServer(poiImage);
                }
            }
        }
    }

    private boolean precheck(PoiImage poiImage) {
        if (poiImage == null) {
            return false;
        }
        String path = poiImage.getPath();
        if (!TextUtils.isEmpty(path) && new File(path).exists()) {
            return true;
        }
        poiImage.delete();
        return false;
    }

    private void uploadToServer(PoiImage poiImage) {
        if (poiImage == null) {
            return;
        }
        try {
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("pic_url", poiImage.getUrl());
            jSONObject.put("longitude", poiImage.getLongitude());
            jSONObject.put("latitude", poiImage.getLatitude());
            jSONObject.put("elevation", poiImage.getAltitude());
            jSONObject.put("create_time", poiImage.getTimestamp());
            jSONObject.put("uuid", poiImage.getWorkoutUUID());
            poiImage.setUploaded(true);
            poiImage.save();
        } catch ( JSONException e) {
            e.printStackTrace();
        }
    }

    private String uploadToUpyun(PoiImage poiImage) {
        Bitmap shrinkBitmap;
        String url = poiImage.getUrl();
        if (!TextUtils.isEmpty(url)) {
            return url;
        }
        return null;
    }
}